package com.atguigu.yygh.hosp.service.impl;

import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.Schedule;

import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;

import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;


import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class  ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveSchedule(Schedule schedule) {
        //判断是否有改排班
        Schedule scheduleDB=scheduleRepository.findByHoscodeAndHosScheduleId(schedule.getHoscode(),schedule.getHosScheduleId());

        if(scheduleDB==null){
            //执行添加

            //未传递的字段
            //不存在执行添加

            //为传递的字段
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);

        }else {

            schedule.setId(scheduleDB.getId());
            //为传递的字段
            schedule.setCreateTime(scheduleDB.getCreateTime());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(scheduleDB.getIsDeleted());

        }

        scheduleRepository.save(schedule);
    }

    @Override
    public Page getScheduleList(String hoscode, Integer page, Integer limit) {
        //查询条件
        Schedule schedule = new Schedule();
        schedule.setHoscode(hoscode);
        Example<Schedule> example = Example.of(schedule);

        //排序

        Sort sort = Sort.by(Sort.Order.asc("hosScheduleId"));
        //分页参数
        PageRequest pageRequest = PageRequest.of(page - 1, limit,sort);

        return scheduleRepository.findAll(example, pageRequest);
    }

    @Override
    public void removeSchedule(String hoscode, String hosScheduleId) {
        Query query = new Query(Criteria.where("hoscode").is(hoscode).and("hosScheduleId").is(hosScheduleId));

        mongoTemplate.remove(query,Schedule.class);
    }

    @Override
    public Map<String, Object> getDateList(Integer page, Integer size, String hoscode, String depcode) {
        //基础条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);

        //查询数量的聚合参数-基础条件,分组
        Aggregation countAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );

        //参数  1.聚合条件 2.集合对应的实体类  3.接受结果的类

        AggregationResults<BookingScheduleRuleVo> countResult = mongoTemplate.aggregate(countAgg,
                Schedule.class, BookingScheduleRuleVo.class);

        //获取数量
        int count = countResult.getMappedResults().size();

        //查询列表的聚合参数--基础条件,分组,求和

        Aggregation listAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
                        .first("workDate").as("workDate")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                Aggregation.sort(Sort.by(Sort.Order.asc("workDate"))),
                Aggregation.skip((page + 1) * size),
                Aggregation.limit(size)
        );


        //执行

        AggregationResults<BookingScheduleRuleVo> listResult = mongoTemplate.aggregate(listAgg,
                Schedule.class, BookingScheduleRuleVo.class);


        // 获取列表
        List<BookingScheduleRuleVo> list = listResult.getMappedResults();
        Map<String, Object> map = new HashMap<>();

        //转换日期为周几
        list.forEach(bookingScheduleRuleVo -> {

            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        });
        map.put("count",count);
        map.put("list",list);
        return map;


    }

    @Override
    public List<Schedule> getDoctorList(String hoscode, String depcode, String workDate) {
        Date date = new DateTime(workDate).toDate();
        return scheduleRepository.findByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,date);
    }


    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }



}
